//
//  DHCleanOrderController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/10.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHCleanOrderController.h"
#import "DHNavbarView.h"
#import "DHOrderButton.h"
#import "DHIsFinishedCell.h"
#import <CoreLocation/CoreLocation.h>
#import "DHCommentController.h"
NSString *finishedCellID = @"finishedCellID";
@interface DHCleanOrderController ()<UITableViewDataSource,UITableViewDelegate,DHIsFinishedCellDelegate,CLLocationManagerDelegate>
@property(nonatomic ,strong)DHNavbarView *navbar; // 导航栏
@property(nonatomic ,strong)UIView *filterView; // 完成、未完成View
@property(nonatomic ,strong)DHOrderButton *finishedBtn;
@property(nonatomic ,strong)DHOrderButton *noFinishedBtn;
@property(nonatomic ,strong)UITableView *finiedCleanView;
@property(nonatomic ,assign)int page;
@property(nonatomic ,strong)DHCleanOrderDataModel *dataModel;
@property(nonatomic ,assign)int status;
@property (nonatomic,strong ) CLLocationManager *locationManager;//定位服务
@property (nonatomic,copy) NSString *currentCity;   //城市
@property (nonatomic,copy) NSString *strLatitude;   //经度
@property (nonatomic,copy) NSString *strLongitude;  //维度
@property(nonatomic ,assign)int type;
@end

@implementation DHCleanOrderController
#pragma mark: - lazy tableView
- (UITableView *)finiedCleanView{
    if (!_finiedCleanView) {
        _finiedCleanView = [[UITableView alloc] init];
        _finiedCleanView.delegate = self;
        _finiedCleanView.dataSource = self;
    }
    return _finiedCleanView;
}

- (void)setDataModel:(DHCleanOrderDataModel *)dataModel
{
    _dataModel = dataModel;
    
    [self.finiedCleanView reloadData];
    [self.finiedCleanView.mj_footer endRefreshing];
    [self.finiedCleanView.mj_header endRefreshing];
}

// lazy filterView
- (UIView *)filterView
{
    if (!_filterView){
        _filterView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navbar.frame), kScreenWidth, 44)];
        _filterView.backgroundColor = UIColor.whiteColor;
        self.finishedBtn = [DHOrderButton orderButtonWithFrame:CGRectMake(0, 0, kScreenWidth / 2, _filterView.bounds.size.height) title:@"已完成"];
        // [orderBtn addTarget:self action:@selector(taskButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        self.finishedBtn.selected = YES;
        
        self.noFinishedBtn = [DHOrderButton orderButtonWithFrame:CGRectMake(CGRectGetMaxX(self.finishedBtn.frame), 0, kScreenWidth / 2, _filterView.bounds.size.height) title:@"未完成"];
        [self.finishedBtn addTarget:self action:@selector(finishedButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.noFinishedBtn addTarget:self action:@selector(noFinishedButtonClick:) forControlEvents:UIControlEventTouchUpInside];

        
        [_filterView addSubview:self.finishedBtn];
        [_filterView addSubview:self.noFinishedBtn];
        
    }
    return _filterView;
}

- (void)locatemap{
    
    if ([CLLocationManager locationServicesEnabled]) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestAlwaysAuthorization];
        _currentCity = [[NSString alloc]init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 5.0;
        [_locationManager startUpdatingLocation];
    }
}

#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]openURL:settingURL];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //当前的经纬度
    NSLog(@"当前的经纬度 %f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    self.strLongitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude];
    self.strLatitude =  [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude];;
    //这里的代码是为了判断didUpdateLocations调用了几次 有可能会出现多次调用 为了避免不必要的麻烦 在这里加个if判断 如果大于1.0就return
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //地理反编码 可以根据坐标(经纬度)确定位置信息(街道 门牌等)
        [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count >0) {
                CLPlacemark *placeMark = placemarks[0];
                self->_currentCity = placeMark.locality;
                if (!self->_currentCity) {
                    self->_currentCity = @"无法定位当前城市";
                }
                //看需求定义一个全局变量来接收赋值
                //            NSLog(@"当前国家 - %@",placeMark.country);//当前国家
                NSLog(@"当前城市 - %@",self->_currentCity);//当前城市
               // self.leftNavButton.titleLabel.text = self->_currentCity;
                //[self.addrBtn setTitle:self->_currentCity forState:UIControlStateNormal];
                //            NSLog(@"当前位置 - %@",placeMark.subLocality);//当前位置
                //            NSLog(@"当前街道 - %@",placeMark.thoroughfare);//当前街道
                //            NSLog(@"具体地址 - %@",placeMark.name);//具体地址
                NSString *message = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",placeMark.country,self->_currentCity,placeMark.subLocality,placeMark.thoroughfare,placeMark.name];
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
                //            [alert show];
            }else if (error == nil && placemarks.count){
                
                NSLog(@"NO location and error return");
            }else if (error){
                
                NSLog(@"loction error:%@",error);
            }
        }];
    });
    [self loadDataWithPullup:NO];
}
#pragma mark: - 已完成事件监听
- (void)finishedButtonClick:(DHOrderButton *)sender
{
    sender.selected = YES;
    self.noFinishedBtn.selected = NO;
    
    self.status = 2;
    [self loadDataWithPullup:NO];
    self.type = 2;

}
#pragma mark: - 未完成事件监听
- (void)noFinishedButtonClick:(DHOrderButton *)sender{
    sender.selected = YES;
    self.finishedBtn.selected = NO;
    
    self.status = 1;
    self.type = 1;
    [self loadDataWithPullup:NO];
}
// lazy navbar
- (DHNavbarView *)navbar{
    if (!_navbar)
    {
        CGRect frame;
        frame = KIsiPhoneX ? CGRectMake(0, 0, kScreenWidth, 88) : CGRectMake(0, 0, kScreenWidth, 64);
        _navbar = [DHNavbarView navbarViewWithFrame:frame title:@"我的清洁订单" isHiddenReturn:NO];
     
    }
    return _navbar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setupUI];
    self.page = 1;
    self.status = 2;
    [self loadDataWithPullup:NO];
    
    [self locatemap];
    
}
#pragma mark: - 加载数据
- (void)loadDataWithPullup:(BOOL)pullup
{
    if (pullup)
    {
        if (!self.dataModel) {return;}
        if (self.dataModel.hasmore.boolValue) {
            self.page++;
        }else{
            [self.finiedCleanView.mj_footer endRefreshingWithNoMoreData];
        }
    }
    [DHNetworkManager.shareManager requestCleanOrderListWithCurpage:[NSString stringWithFormat:@"%d",self.page] status:[NSString stringWithFormat:@"%d",self.status] is_store:@"0" is_mouth:self.is_mouth finishedBlock:^(BOOL isSuccess, DHCleanOrderDataModel *datasModel)
     {
         if (!isSuccess) {
             [SVProgressHUD showErrorWithStatus:@"网络出错"];
             [self.finiedCleanView.mj_footer endRefreshing];
             return ;
         }
         if (pullup) {
             
             self.dataModel.list = [self.dataModel.list arrayByAddingObjectsFromArray:datasModel.list];
         }else{
             self.dataModel = datasModel;
         }
    }];
}
#pragma mark: - 设置界面
- (void)setupUI
{
    [self.view setBackgroundColor:UIColor.whiteColor];
    [self.view addSubview:self.navbar];
    [self.view addSubview:self.filterView];
    __weak typeof(self) WeakSelf = self;
    self.navbar.popButtonClickBlock = ^{
        [WeakSelf.navigationController popViewControllerAnimated:true];
    };
    self.finiedCleanView.frame = CGRectMake(0, CGRectGetMaxY(self.filterView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.filterView.frame));
    
    [self.view addSubview:self.finiedCleanView];
    //self.title = @"我的清洁订单"
    self.finiedCleanView.rowHeight = 120;
    [self.finiedCleanView registerNib:[UINib nibWithNibName:@"DHIsFinishedCell" bundle:nil] forCellReuseIdentifier:finishedCellID];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:
                                     ^{
                                         [self loadDataWithPullup:NO];
                                     }];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadDataWithPullup:YES];
    }];
    self.finiedCleanView.mj_header = header;
    self.finiedCleanView.mj_footer = footer;
    self.finiedCleanView.tableFooterView = [[UIView alloc] init];

}
#pragma mark: - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataModel.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DHIsFinishedCell *cell = [tableView dequeueReusableCellWithIdentifier:finishedCellID forIndexPath:indexPath];
    cell.model = self.dataModel.list[indexPath.row];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark: - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DHOrderDetailController *detailVC = [[DHOrderDetailController alloc] init];
    detailVC.hidesBottomBarWhenPushed = true;
    
    NSMutableDictionary *requestInfo = [NSMutableDictionary dictionary];
    requestInfo[@"id"] = self.dataModel.list[indexPath.row].ID;
    requestInfo[@"lng"] = self.strLongitude;
    requestInfo[@"lat"] = self.strLatitude;
    detailVC.requestInfo = requestInfo.copy;
    
    [self.navigationController pushViewController:detailVC animated:true];
}

#pragma mark: - DHIsFinishedCellDelegate
- (void)finishedCellDidGoCommectButtonClick:(DHIsFinishedCell *)cell
{
    if (cell.model.status.intValue != 2) {
        [self postFinishedOrderWithID:cell.model.ID];
    }
    DHCommentController *comment = [[DHCommentController alloc] init];
    NSMutableDictionary *postEvaParam = [NSMutableDictionary dictionary];
    postEvaParam[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    postEvaParam[@"id"] = cell.model.ID;
    postEvaParam[@"order_id"] = cell.model.order_id;
    postEvaParam[@"cleaner_id"] = cell.model.member_id;
    postEvaParam[@"type"] = @"1";
    comment.postEvaParam = postEvaParam;
    [self.navigationController pushViewController:comment animated:true];
}
#pragma mark: - 完成订单网络请求
- (void)postFinishedOrderWithID:(NSString *)ID
{
    NSString *url = [NSString stringWithFormat:@"%@%@",REMOTEURL,@"index.php?act=hotel_cleaning&op=runUserDoneOrder"];
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    dictM[@"id"] = ID;
    dictM[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    [DHNetworkManager.shareManager requestWithMethod:MethodPost UrlString:url params:dictM.copy completion:^(id json, BOOL isSuccess)
    {
        if (!isSuccess) {
            [SVProgressHUD showInfoWithStatus:@"请检查网络"];
            return ;
        }
        
        id temp = json[@"datas"];
        
        if (temp[@"succ"]) {
            [SVProgressHUD showSuccessWithStatus:temp[@"succ"]];
        }else{
            [SVProgressHUD showInfoWithStatus:temp[@"error"]];
        }
       
    }];
    
}
@end
